import { addMenu, getAllMenu, removeMenu, updateMenu } from '@/services/ant-design-pro/api';
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import { useIntl } from '@umijs/max';
import { Button, message, Popover } from 'antd';
import React, { useRef, useState } from 'react';
import EditForm from './componets/EditForm';

const filterValueEnum = (
  id: number | undefined,
  valueEnum: { value: number | undefined; label: string }[],
) => {
  return valueEnum.filter((item) => item.value !== id);
};

/**
 * @en-US Add menu
 * @zh-CN 添加菜单
 * @param fields
 */
const handleAdd = async (fields: API.MenuItem) => {
  const hide = message.loading('正在添加');
  try {
    await addMenu({ ...fields });
    hide();
    message.success('Added successfully');
    return true;
  } catch (error) {
    hide();
    message.error('Adding failed, please try again!');
    return false;
  }
};

/**
 * @en-US Update menu
 * @zh-CN 更新菜单
 * @param fields
 */
const handleUpdate = async (fields: API.MenuItem) => {
  const hide = message.loading('正在更新');
  try {
    await updateMenu({ ...fields });
    hide();
    message.success('Updated successfully');
    return true;
  } catch (error) {
    hide();
    message.error('Updating failed, please try again!');
    return false;
  }
};

/**
 * @en-US Delete menu
 * @zh-CN 删除菜单
 * @returns
 */
const handleDelete = async (fields: API.MenuItem) => {
  const hide = message.loading('正在删除');
  try {
    const ret = await removeMenu({ ...fields });
    if (ret['success'] === true) {
      hide();
      message.success('Deleted successfully');
      return true;
    } else {
      hide();
      message.error(ret['errorMessage']);
      return false;
    }
  } catch (error) {
    hide();
    message.error('Deleting failed, please try again!');
    return false;
  }
};

const MenuList: React.FC = () => {
  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */
  const intl = useIntl();

  const actionRef = useRef<ActionType>();

  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  const [createModalOpen, handleModalOpen] = useState<boolean>(false);

  /**
   * @en-US Pop-up children window of new window
   * @zh-CN 新增子菜单窗口的弹窗
   *  */
  const [createChildrenModalOpen, handleCreateChildrenModalOpen] = useState<boolean>(false);

  /**
   * @en-US Pop-up window of edit window
   * @zh-CN 编辑窗口的弹窗
   *  */
  const [editModalOpen, handleEditModalOpen] = useState<boolean>(false);

  const [currentRow, setCurrentRow] = useState<API.MenuItem>();

  const [valueEnum, setValueEnum] = useState<{ value: number | undefined; label: string }[]>([]);

  const columns: ProColumns<API.MenuItem>[] = [
    { title: '菜单ID', dataIndex: 'id', fixed: 'left', valueType: 'digit' },
    { title: '路由', dataIndex: 'path', fixed: 'left' },
    { title: '路由名称', dataIndex: 'name', fixed: 'left' },
    { title: '菜单名称', dataIndex: 'title', fixed: 'left' },
    { title: '父节点', dataIndex: 'parentId', fixed: 'left', valueType: 'digit' },
    {
      title: '是否隐藏',
      dataIndex: 'hidden',
      fixed: 'left',
      valueEnum: {
        true: { text: '隐藏', status: 'Error' },
        false: { text: '显示', status: 'Success' },
      },
    },
    { title: '排序', dataIndex: 'sort', fixed: 'left', valueType: 'digit' },
    {
      title: '操作',
      fixed: 'right',
      valueType: 'option',
      render: (_, record) => [
        <Button
          key="add"
          onClick={() => {
            setCurrentRow(record);
            handleCreateChildrenModalOpen(true);
          }}
          type="primary"
        >
          添加子菜单
        </Button>,
        <Button
          key="编辑"
          onClick={() => {
            setCurrentRow(record);
            handleEditModalOpen(true);
          }}
          type="primary"
        >
          编辑
        </Button>,
        <Popover
          key="delete"
          content={
            <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
              <p style={{ marginBottom: 8 }}>您确定要删除这个菜单吗？如有子菜单不可删除</p>
              <div style={{ display: 'flex', justifyContent: 'center' }}>
                <Button
                  type="primary"
                  danger
                  style={{ marginRight: 8 }}
                  onClick={async () => {
                    const success = await handleDelete(record);
                    if (success) {
                      if (actionRef.current) {
                        actionRef.current.reload();
                      }
                    }
                  }}
                >
                  确认
                </Button>
                <Button>取消</Button>
              </div>
            </div>
          }
        >
          <Button type="primary" danger>
            删除
          </Button>
        </Popover>,
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable<API.MenuItem>
        actionRef={actionRef}
        rowKey="id"
        search={false}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalOpen(true);
            }}
          >
            <PlusOutlined /> 新增根菜单
          </Button>,
        ]}
        request={async () => {
          const res = await getAllMenu();
          const valueEnum: { value: number | undefined; label: string }[] = [];

          function fillValueEnum(value: API.MenuItem) {
            valueEnum.push({ value: value.id, label: value.title as string });
            value.children = value.routes;
            value.routes?.forEach(fillValueEnum);
          }

          res.data?.forEach(fillValueEnum);

          valueEnum.unshift({ value: undefined, label: '根菜单' });

          setValueEnum(valueEnum);
          return res;
        }}
        columns={columns}
        pagination={false}
      />
      <EditForm
        title="新增根菜单"
        open={createModalOpen}
        onOpenChange={handleModalOpen}
        onFinish={async (value) => {
          const success = await handleAdd(value);
          if (success) {
            handleModalOpen(false);
            setCurrentRow(undefined);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        values={{ isFixParent: true, fixParentId: undefined, valueEnum: valueEnum }}
      />
      <EditForm
        title="新增子菜单"
        open={createChildrenModalOpen}
        onOpenChange={handleCreateChildrenModalOpen}
        onFinish={async (value) => {
          const success = await handleAdd(value);
          if (success) {
            handleCreateChildrenModalOpen(false);
            setCurrentRow(undefined);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        values={{ isFixParent: true, fixParentId: currentRow?.id, valueEnum: valueEnum }}
      />
      <EditForm
        title="编辑菜单"
        open={editModalOpen}
        onOpenChange={handleEditModalOpen}
        onFinish={async (value) => {
          const success = await handleUpdate(value);
          if (success) {
            handleEditModalOpen(false);
            setCurrentRow(undefined);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        values={{
          ...currentRow,
          isFixParent: false,
          fixParentId: undefined,
          valueEnum: filterValueEnum(currentRow?.id, valueEnum),
        }}
      />
    </PageContainer>
  );
};

export default MenuList;
